<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'

import { useAddProductBrand, useEditProductBrand, useGetProductBrandDetail } from '@fl/api/supplier'
import FlUpload from '@fl/components/fl-upload.vue'
import SubmitBtn from '@fl/components/submit-btn.vue'
import { cloneDeep } from 'lodash-es'

const id = defineModel<string>('id', { required: true })
const visible = defineModel<boolean>('visible', { required: true })

const initialState = { brandLogo: '' } as any
const state = ref(cloneDeep(initialState))

const isEdit = computed(() => !!id.value)
const dialogTitle = computed(() => isEdit.value ? '编辑品牌' : '新增品牌')

const { isPending: isAddProductBrandPending, mutate: addProductBrand } = useAddProductBrand()
const { isPending: isEditProductBrandPending, mutate: editProductBrand } = useEditProductBrand()
const { data: productBrandDetailData, isLoading: isGetProductBrandDetailLoading } = useGetProductBrandDetail(id)

// #region Form
const formRef = ref()
const isFormLoading = computed(() => isEdit.value && isGetProductBrandDetailLoading.value)
const isSubmitLoading = computed(() => isEdit.value ? isEditProductBrandPending.value : isAddProductBrandPending.value)

const columns: PlusColumn[] = [
    {
        fieldProps: {
            maxlength: 20,
            onChange: (value: string) => { state.value.brandName = value.replace(/\s+/g, '') },
            showWordLimit: true,
        },
        label: '品牌名称',
        prop: 'brandName',
        valueType: 'copy',
    },
    {
        label: '品牌拼音',
        prop: 'brandPinyin',
        valueType: 'copy',
    },
    {
        label: '品牌英文名',
        prop: 'brandEnglishName',
        valueType: 'copy',
    },
    {
        label: '品牌LOGO',
        prop: 'brandLogo',
    },
]

const rules = {
    brandEnglishName: [
        {
            required: true,
            validator: (_rule: any, value: any, callback: any) => {
                const regex = /^[A-Z]+$/i
                if (!value) {
                    callback(new Error('请输入品牌英文名'))
                }
                else if (!regex.test(value)) {
                    callback(new Error('请输入英文字符'))
                }
                else {
                    callback()
                }
            },
        },
    ],
    brandLogo: [
        {
            message: '请选择品牌LOGO',
            required: true,
            trigger: 'change',
        },
    ],
    brandName: [
        {
            message: '请输入品牌名称',
            required: true,
            trigger: 'change',
        },
    ],
    brandPinyin: [
        {
            required: true,
            validator: (_rule: any, value: any, callback: any) => {
                const regex = /^[A-Z]+$/i
                if (!value) {
                    callback(new Error('请输入品牌拼音'))
                }
                else if (!regex.test(value)) {
                    callback(new Error('请输入英文字符'))
                }
                else {
                    callback()
                }
            },
        },
    ],
}

function cancel() {
    visible.value = false
}

function closed() {
    if (isEdit.value) {
        id.value = ''
    }
    else {
        state.value = cloneDeep(initialState)
        formRef.value.formInstance?.resetFields()
    }
}
// #endregion

// #region UI Listener
function onSubmitBtnClick() {
    formRef.value.handleSubmit()
}

function submit() {
    const params = {
        ...state.value,
    }
    if (isEdit.value) {
        params.id = id.value
    }

    const fn = isEdit.value ? editProductBrand : addProductBrand
    fn(params, {
        onSuccess() {
            ElMessage.success('操作成功')
            cancel()
        },
    })
}
// #endregion

watchEffect(() => {
    if (isEdit.value && productBrandDetailData.value) {
        Object.assign(state.value, productBrandDetailData.value)
    }
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialogTitle"
                width="700"
                close-on-press-escape
                @cancel="cancel"
                @closed="closed"
    >
        <el-skeleton v-if="isFormLoading"
                     animated
        />

        <PlusForm v-else
                  ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="100"
                  :rules="rules"
                  :has-footer="false"
                  :row-props="{ gutter: 40 }"
                  @submit="submit"
        >
            <template #plus-field-brandLogo>
                <FlUpload v-model="state.brandLogo"
                          tips
                          accept=".jpg,.jpeg,.png"
                />
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isSubmitLoading"
                           @click="onSubmitBtnClick"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
